package edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class OkHttpUtils {

    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10000, TimeUnit.MILLISECONDS)
            .readTimeout(10000, TimeUnit.MILLISECONDS)
            .build();

    /**
     * 发送POST请求，传递Map参数
     * 设计原则体现：
     * 1. 单一职责原则(SRP) - 方法只负责发送POST请求
     * 2. 关注点分离 - 请求构建与发送逻辑分离
     */
    public static String postMap(String url, Map<String, Object> param) throws UnsupportedEncodingException {
        FormBody.Builder builder = new FormBody.Builder();

        for (String key : param.keySet()) {
            Object obj = param.get(key);
            if (obj != null) {
                builder.addEncoded(key, param.get(key).toString());
            } else {
                builder.addEncoded(key, "");
            }
        }
        FormBody requestBody = builder.build();

        Request request = new Request.Builder().url(url)
                .post(requestBody)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            System.out.println(response.code() + "," + response.body());
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    /**
     * 发送POST请求，传递JSON参数和Authorization头
     * 设计原则体现：
     * 1. 高内聚 - 方法功能单一，专注于发送JSON请求
     * 2. 依赖注入原则(DI) - 通过参数传递依赖
     */
    public static String postJsonHead(String url, JSONObject params, String token) throws IOException {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

        RequestBody requestBody = RequestBody.create(mediaType, JSON.toJSONString(params));
        String string = okHttpClient.newCall(new Request.Builder()
                        .header("Authorization", "Bearer " + token)
                        .url(url)
                        .post(requestBody)
                        .build())
                .execute()
                .body()
                .string();
        return string;
    }

    /**
     * 发送POST请求，传递JSON字符串和Authorization头
     * 设计原则体现：
     * 1. 关注点分离 - 请求构建与发送逻辑分离
     * 2. 日志记录 - 记录请求和响应信息，便于调试
     */
    public static String postJsonStringHead(String url, String json, String token) throws IOException {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

        RequestBody requestBody = RequestBody.create(mediaType, json);
        String string = okHttpClient.newCall(new Request.Builder()
                        .header("Authorization", "Bearer " + token)
                        .header("Content-Type", "application/json")
                        .url(url)
                        .post(requestBody)
                        .build())
                .execute()
                .body()
                .string();
        log.info("OkHttpUtils.post{}", JSON.toJSONString(url));
        log.info("OkHttpUtils.post{}", json + "=======result:" + string);
        return string;
    }
}
